import axios from 'axios'

// 创建axios实例
const service = axios.create({
  baseURL: ``,
  timeout: 30 * 1000, // 请求超时时间
})



//获取token
const getToken = () => {
  return localStorage.getItem(`chaofanonlineAccessToken`) || ``
}

const refreshToken = () => {
  let refresh_token = localStorage.getItem(`chaofanonlineRefreshToken`) || ``;
  if (!refresh_token) {
    return Promise.reject(`请先登录`);
  }
  return axios.post(`https://www.chaofan.online/api/v1/token/refresh`, { refresh: refresh_token });
}

service.interceptors.request.use(
  (config) => {
    if (/^(?:post|put|delete)$/i.test(`${config.method}`)) {
      if (config.data && config.data.upload) {
        config.headers[`Content-Type`] = `multipart/form-data`
      }
      // console.log(`请求头`, config)
      //如果请求的url是https://www.chaofan.online开头或者以localStorage.getItem(`chaofanonlineobjectstorageBaseUrl`)开头的，则添加token
      if (config.url?.startsWith(`https://www.chaofan.online`) || config.url?.startsWith(localStorage.getItem(`chaofanonlineobjectstorageBaseUrl`) || "")) {
        // console.log("即将请求chaofan.online")
        config.headers[`Authorization`] = `Bearer ${getToken()}`
      }
      // if (/^https:\/\/www.chaofan.online/.test(`${config.url}`)) {
      //   config.headers[`Authorization`] = `Bearer ${getToken()}`
      //   console.log(`请求头`, config.headers)
      // }



    }
    return config
  },
  (error) => {
    Promise.reject(error)
  },
)

service.interceptors.response.use(
  (res) => {
    return res.data ? res.data : Promise.reject(res)
  },
  async (error) => {
    if (error.response.data.code === "token_not_valid") {
      return refreshToken().then(res => {
        localStorage.setItem(`chaofanonlineAccessToken`, res.data.access);
        localStorage.setItem(`chaofanonlineRefreshToken`, res.data.refresh);
        console.log(`token刷新成功`);
        return service(error.config);
      }).catch(error => {
        return Promise.reject(error);
      });
    }

    return Promise.reject(error)
  }
)

export default service
